package kuzha.runtime;

import java.util.ListIterator;
import java.util.NoSuchElementException;

import kuzha.KuzhaObject;

public class RangeListIterator implements ListIterator<KuzhaObject> {
	private final RangeList owner;
	private int index = 0;
	
	public RangeListIterator(RangeList owner) {
		this.owner = owner;
	}
	public RangeListIterator(RangeList owner, int index) {
		this.owner = owner;
		this.index = index;
	}
	
	@Override
	public boolean hasNext() {
		return owner.isInfiniteList() || index < owner.size();
	}
	@Override
	public KuzhaObject next() {
		if (hasNext())
			return owner.get(index++);
		else
			throw new NoSuchElementException();
	}
	@Override
	public void remove() {
		int back = index - 1;
		if (0 <= back && back < owner.size()) {
			owner.remove(back);
			index--;
			return;
		}
		throw new NoSuchElementException();
	}
	
	@Override
	public void add(KuzhaObject e) {
		owner.add(index++, e);
	}
	@Override
	public boolean hasPrevious() {
		return 0 < index;
	}
	@Override
	public int nextIndex() {
		return index + 1;
	}
	@Override
	public KuzhaObject previous() {
		if (hasPrevious())
			return owner.get(--index);
		else
			throw new NoSuchElementException();
	}
	@Override
	public int previousIndex() {
		return index - 1;
	}
	@Override
	public void set(KuzhaObject e) {
		owner.set(index, e);
	}
}
